<template>
    <div>
        <GmapAutocomplete :value='searchValue' v-if='showSearch' @place_changed="setPlace" :position.sync='searchMarker'>

        </GmapAutocomplete>
        <GmapMap class='map' :style="{height:options.height}" 
            ref='googlemap' :center="centers" :places="places" 
            :zoom="zoom" :options='mapOptions'
            :map-type-id="options.mapType" @click="clicked">
            <GmapCluster :zoomOnClick="true">
                <GmapMarker ref="vehicleMarker" :key="index" v-for="(item,index) in markers" :title="item.title" :label='item.label'
                    :position="item.position" :visible='item.visible' :clickable="true" :draggable="false" @click="handleMarker(item)"
                    :icon.sync="item.icon" />
            </GmapCluster>
            <!-- <GmapMarker v-for="(marker, index) in markers" :key="index" :position="marker.position" /> -->
            <GmapMarker v-if="searchMarker" label="★" :position="searchMarker" />
            <!-- 信息弹窗 -->
            <GmapMarker label="★" :position="options.position" />
            <GmapInfoWindow :opened='isOpenInfoWin' :options='infoWinOptions' :position='infoWinPos' @closeclick="infoWindowClose">
                <div v-if='options.infos && options.infos.alarmTypeName'>
                    <p>{{options.infos.alarmTypeName}}</p>
                    <p>{{parseTime(options.infos.time)}}</p>
                </div>
                <Infowindow :form='markerInfo' />
            </GmapInfoWindow>
            
            <!-- 分段轨迹 -->
            <GmapPolyline :path="sectionPath" :options='secPolylineOptions' :editable="false" @path_changed="updateEdited($event)" ref="polyline">
            </GmapPolyline>
            <!-- 起始点 -->
            <GmapMarker :key="index+'1'" v-for="(item,index) in pointsMarker" :position="item.position" :clickable="true" :draggable="false"
                :icon.sync="item.icon" />
            <!-- 车辆标记 -->
            <GmapMarker :key="item.name" v-for="item in moveVehicleMarkers" :position="item.position" :clickable="true" :draggable="false"
                :icon.sync="item.icon" />
        </GmapMap>
    </div>
</template>

<script>
import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-maps'
import GmapCluster from 'vue2-google-maps/dist/components/cluster'
import Infowindow from './Infowindow'
import  GmapDrawingManager  from 'vue2-google-maps';

import { vehicleMonitorDetail } from "@/api/vehicle/position/data";
import { gmapApi } from 'vue2-google-maps'
import { log } from 'console';
Vue.use(VueGoogleMaps, {
    load: {
        key: 'AIzaSyC6EIUR3I08i9DJpdnTs_stLH9jzNE594M',
        libraries: 'places,drawing', // This is required if you use the Autocomplete plugin
        v: '3.26',
        // OR: libraries: 'places,drawing'
        // OR: libraries: 'places,drawing,visualization'
        // (as you require)

        //// If you want to set the version, you can do so:
        // v: '3.26',
    }
})

Vue.component('GmapCluster', GmapCluster)
Vue.component('GmapDrawingManager', GmapDrawingManager)
export default {
    name: 'GMap',
    components: { GmapCluster, Infowindow,GmapDrawingManager },
    props: {
        options: {
            type: Object,
            default: () => {
                return {
                    mapType: 'roadmap',
                    position: { lat: 51.5073509, lng: -0.1277583 },
                    isSearch: false, //是否显示搜索框
                    showInfo: false, //是否显示信息弹框
                    isTrack: false, //是否显示轨迹
                    height: '300px', //地图的高度
                    posList: [], //gps数组,
                    trackList: [], //轨迹数组
                    infos: {}, //信息弹框的内容
                    address: '', //地址
                    state: 0  //设备状态

                }
            }
        }
    },
    data() {
        return {
            centers: {
                lat: 46.8182, lng: 8.2275
            },
            zoom: 10,
            place: null,
            places: {},
            searchValue: '',
            searchMarker: {},
            locations: [],
            loading: false,
            markers: [],
            showSearch: false,
            mapOptions: {
                mapTypeControl: false,
                streetViewControl: false,
                zoomControl: false,
                fullscreenControl: false,
                clickableIcons: false, //点击地点不出现浮窗
                scaleControl: true,
            },
            sectionPath: [],
            secPolylineOptions: {
                strokeColor: '#029801',
                strokeOpacity: '1',
                strokeWeight: 4,
                visible: true
            },
            boundCenter: null,
            pointsMarker: [],
            moveVehicleMarkers: [],
            //行程轨迹数组的车辆标记位置
            vehicleMarkers: [],
            trackList:[],
            infoWinOptions: {
                    pixelOffset:{
                        width:0,
                        height: -35
                    }
            },
            infoWinPos: {
                lat: 0,
                lng: 0
            },
            isOpenInfoWin: false,
            animation: null,
            icons: [require('@/assets/images/onLine.png'), require('@/assets/images/offLine.png'), require('@/assets/images/park.png')],
            markerInfo: {},
            oMarkers: [],
            count:0,
            cancel:0,
            map:null,
            drawingManager:null
        }

    },
    computed: {
        google: gmapApi
    },
    watch: {
        options: {
            handler: function (val) {
                this.posList = val.posList;
                
                if (val.isSearch) {
                    this.searchValue = val.address;
                    this.searchMarker = val.position;
                    this.showSearch = val.isSearch;
                    this.$nextTick(() => {
                        this.$refs.googlemap.panTo(val.position);
                    })
                    this.zoom = 5;
                }

                if (val.showInfo) {
                    this.isOpenInfoWin = true;
                    this.infoWinPos = val.position;
                    this.$nextTick(() => {
                        this.$refs.googlemap.panTo(val.position);
                    })
                    this.zoom = 5;
                }
                    console.log(val);
                if (val.isTrack && val.trackList.length) {
                    console.log(val);
                    this.$nextTick(() => {
                        //gps的数组
                        this.sectionPath = val.trackList;
                        //设置起始和结束的标记点
                        this.pointsMarker = this.setStartEndPoint(this.sectionPath);
                        this.vehicleMarkers = this.setMoveVehicle(this.sectionPath, true)
                        this.setCenters(val.posList);

                        this.$refs.googlemap.panTo(val.trackList[0]);
                        this.zoom = 20;

                    })

                }
                if (!val.isTrack && val.posList.length) {
                    if (this.markers.length) {
                        this.isOpenInfoWin = false;
                        this.markers = this.setMoveVehicle(val.posList);
                        this.markers.forEach(item => {
                            item.visible = val.state ? (item.content.state === val.state ? true : false) : true
                        })
                    } else {
                        this.$nextTick(() => {
                            this.markers = this.setMoveVehicle(val.posList);
                            this.oMarkers = [...this.markers]

                        })
                    }

                    this.setCenters(val.posList);

                }
                if (val.posList.length == 0) {
                    this.markers = [];
                }

              

            },
            immediate: true,
            deep: true,
            
        }
    },
    mounted() {
        
         this.map = new google.maps.Map(this.$refs.googlemap, {
                center: { lat: -34.397, lng: 150.644 },
             zoom: 15,
        });
    this.drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.MARKER,
      drawingControl: true,
      drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle'],
      },
    });
    this.drawingManager.setMap(map);
  },
    methods: {
        clicked() { },
        infoWindowClose() {
            this.isOpenInfoWin = false;
        },
        onOverlayComplete(e) {
      // 当用户完成电子围栏的绘制后，这个方法会被调用
      // e.overlay 是绘制的多边形对象
      // 你可以从这个对象中获取多边形的顶点坐标等信息
      const polygon = e.overlay;
      const path = polygon.getPath().getArray();
      console.log(path.map(p => ({ lat: p.lat(), lng: p.lng() })));
      
      // 根据需要，你可以将这些坐标保存到数据库中
    },
        handleMarker(item) {
                console.log(item);
                console.log(this.markers);
            vehicleMonitorDetail({ deviceCode: item.deviceCode }).then(res => { 
                    console.log("点击某个详情");
                if(this.count >= 1){
                    this.isOpenInfoWin = false;
                    this.count = 0;
                    this.handleMarker(item)
                }
                else if (res.data.lat || res.data.lng) {
                    // this.getAddress(res.data.lat,res.data.lng)
                    this.markerInfo = res.data;
                    this.infoWinPos = { lat:parseFloat(item.position.lat), lng: parseFloat(item.position.lng) };
                    this.isOpenInfoWin = true;
                    console.log("经纬度",this.infoWinPos);
                    this.centers = this.infoWinPos
                    this.$refs.googlemap.panTo(this.infoWinPos) //平滑到以点开的标记的经纬度为中心点的地方
                    // this.zoom = 15;
                    this.count++;
                }
                
                
                if(this.cancel==0 &&(res.data.lat == null || res.data.lng == null)){
                    this.msgSuccess(this.$t('prompt.noGps'));
                    this.cancel++;
                }else{
                    this.cancel =0;
                }
                

            })

        },
        handleMarkerclose(){
             this.isOpenInfoWin = false;
        },
        //设置搜索位置
        setPlace(place) {
            this.searchValue = place.formatted_address + place.name
            this.place = place;
            this.searchMarker = {
                lat: this.place.geometry.location.lat(),
                lng: this.place.geometry.location.lng(),
            }
            this.$refs.map.panTo(this.searchMarker);
            this.zoom = 5;

            const params = {
                address: this.place.formatted_address + this.place.name,
                position: this.searchMarker
            }
            this.$emit('searchAddress', params)
        },
        //设置中心点
        setCenters(list) {
            this.boundCenter = new google.maps.LatLngBounds();
            if (list && list.length) {
                list.forEach(item => {
                    if (item.lat || item.lng) {
                        this.boundCenter.extend(new google.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng)))
                    }
                })
            }
            this.$refs.googlemap.$mapObject.fitBounds(this.boundCenter);
            const centerLatLng = new google.maps.LatLng(46.8182, 8.2275);
            // this.$refs.googlemap.$mapObject.setCenter(centerLatLng)  //使所有点在地图居中
            this.$refs.googlemap.$mapObject.setZoom(4);
            this.$refs.googlemap.$mapObject.setCenter(this.boundCenter.getCenter())  //使所有点在地图居中
        },
        //设置起始结束点标记
        setStartEndPoint(list) {
            let points = [];
            //起始点
            let sPoint = {
                position: {
                    lng: parseFloat(list[0].lng),
                    lat: parseFloat(list[0].lat)
                },
                icon: {
                    url: require('@/assets/images/startNew.png'),
                    size: { width: 30, height: 40 }
                },
                name: 'start' + list[0].direction
            }
            //结束点
            let ePoint = {
                position: {
                    lng: parseFloat(list[list.length - 1].lng),
                    lat: parseFloat(list[list.length - 1].lat)
                },
                icon: {
                    url: require('@/assets/images/endNew.png'),
                    size: { width: 30, height: 40 }
                },
                name: 'end' + list[0].direction
            }
            points.push(sPoint, ePoint);
            return points;
        },
        //设置车辆位置标记, isMove:表示移动车辆
        setMoveVehicle(list, isMove = false) {
            let vehicleMakers = []
            list.forEach(item => {

                if (item.lat || item.lng) {
                    const url = item.state === 1 ? this.icons[1] : item.state === 2 ? this.icons[0] : this.icons[2];
                    let vMarker = {
                        deviceCode: !isMove ? item.deviceCode : undefined,
                        title: !isMove ? item.vehicleType : undefined,
                        position: {
                            lat: parseFloat(item.lat),
                            lng: parseFloat(item.lng)
                        },
                        icon: {
                            url: isMove ? this.icons[0] : url,
                            size: {
                                width: 39,
                                height: 55
                            },
                            labelOrigin: { x: 20, y: 70 },
                            scaledSize: new google.maps.Size(39, 55)
                        },
                        name: 'vehicle' + item.direction,
                        content: isMove ? '' : item,
                        visible: true,
                        label: isMove ? '' : { color: '#ffffff', className: 'map_label', text: item.vehicleType }
                    }
                    vehicleMakers.push(vMarker);
                }
            })
            return vehicleMakers;
        },
        //车辆移动
        handleVehicleMove(index, flag,) {
            if (index >= this.vehicleMarkers.length) {
                return;
            }
            this.moveVehicleMarkers = [];
            this.moveVehicleMarkers.push(this.vehicleMarkers[index]);
            if (!this.boundCenter.contains(this.vehicleMarkers[index].position)) {
                this.centers = this.vehicleMarkers[index].position
                this.$refs.googlemap.panTo(this.vehicleMarkers[index].position)
            }
        },



        openInfoWindowClickOneMore(item) {
            console.log(item);
             vehicleMonitorDetail({ deviceCode: item.deviceCode }).then((res) => {
                if (res.data.lat || res.data.lng) {
            //将获取到的位置信息存储到 markerInfo 中。
                   var obj = this.posList.filter((v) =>{
                        if (v.deviceCode == item.deviceCode) {
                            return{
                                lat:v.lat,
                                lng:v.lng,
                                deviceCode:v.deviceCode
                            }
                        }
                        
                    })
                        // this.handleMarker(obj[0])
                    this.markerInfo = res.data;
                    this.isOpenInfoWin = true;
                    this.infoWinPos = { lat:parseFloat(obj[0].lat), lng: parseFloat(obj[0].lng) };
                    console.log("经纬度",this.infoWinPos);
                    this.centers = this.infoWinPos
                    this.$refs.googlemap.panTo(this.infoWinPos) //平滑到以点开的标记的经纬度为中心点的地方
                    this.zoom = 25;
                    this.count++;
                    setTimeout(() => {
                    // this.isOpenInfoWin = true;
                    this.infoWinPos = { lat:parseFloat(obj[0].lat), lng: parseFloat(obj[0].lng) };
                    this.$refs.googlemap.panTo(this.infoWinPos) //平滑到以点开的标记的经纬度为中心点的地方
                    }, 1);
                    
         
                }
          

        //   如果获取到的位置信息为空（即没有获取到经纬度），则给用户提示，表示没有获取到 GPS 信号。
          if (res.data.lat == null || res.data.lng == null || res.data.lat == 0 || res.data.lng == 0) {
            this.$modal.msgError(this.$t("vehicle.position.noGps"));
            this.cancel++;
          } else {
            this.cancel = 0;
          }
             });
           
            
       
           
             
        },
        updateEdited(val){},
        getAddress(latitude, longitude) {
            // 使用 Google Maps Geocoding API
            const geocoder = new google.maps.Geocoder();
            const latlng = { lat: latitude, lng: longitude };

            // 调用 geocode 方法获取地址信息
            geocoder.geocode({ location: latlng }, (results, status) => {
                if (status === 'OK') {
                    if (results[0]) {
                        // 获取到第一个结果的地址信息
                        const address = results[0].formatted_address;
                        
                        this.markerInfo.address = address;


                    } else {
                        console.log('No results found');
                    }
                } else {
                    console.log('Geocoder failed due to: ' + status);
                }
            });
        }
      
    }
}
</script>

<style lang='scss'>
.map {
    width: 100%;
    margin-top: 10px;
    
}
.pac-target-input:not(:-webkit-autofill) {
    position: absolute;
    z-index: 8;
    width: 100%;
    height: 40px;
    line-height: 40px;
    border: 1px solid #dcdfe6;
    outline: none;
    padding-left: 15px;
}
.pac-target-input:focus {
    border: 1px solid #409eff;
}
.pac-container {
    z-index: 9999;
}
.map_label {
    background: rgba(0, 0, 0, 0.7);
    line-height: padding;
    /* padding: 10px; */
    height: 32px;
    border-radius: 16px;
    line-height: 32px;
    padding: 0 10px;
    color: #fff;
    font-weight: 600;
}
</style>
